package com.example.base.base

import android.view.KeyEvent
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.viewbinding.ViewBinding
import com.example.base.R
import com.example.base.base.util.postUI

open class BaseFragment : Fragment {

    constructor() : super()
    constructor(@LayoutRes contentLayoutId: Int) : super(contentLayoutId)

    override fun onResume() {
        super.onResume()
        getFocus()
    }

    private fun getFocus() {
        val view = view ?: return
        view.isFocusableInTouchMode = true
        view.requestFocus()
        view.setOnKeyListener { v, keyCode, event ->
            if (event.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                return@setOnKeyListener onBackPressed()
            }
            return@setOnKeyListener false
        }
    }

    /**
     *  返回键监听
     */
    open fun onBackPressed(): Boolean {
        return false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        view?.setOnTouchListener(null)
    }

    open fun close() {
        postUI {
            val fm = parentFragmentManager ?: return@postUI
            val fragment = this
            fm.commit { remove(fragment) }
        }
    }
}